﻿using GetData;
using GetData.webProductClass;
using jutehui.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace jutehui.GetData
{
    public class SMZDMFX
    {
        HtmlAgilityPack.HtmlDocument doc;
        public SMZDMFX()
        {
            doc = new HtmlAgilityPack.HtmlDocument();

        }
        /// <summary>
        /// 什么值得买 HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL(string url, int navType)
        {
            //  List<Product> productList = new List<Product>();
            var productList = GetProductByRegexToHtml(url, navType);
            if (productList == null || productList.Count < 1)
            {
                return "网络异常，未能获取数据";
            }
            // GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string errorMsg = "";
            dt = CustomMethod.ListToDataTable<Product>(productList, "Product", ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product bll = new jutehui.BLL.Product();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            {
                return msg;
            }
        }
        /// <summary>
        /// 将获取的html代码经过正则获取商品信息返回
        /// </summary>
        /// <returns></returns>
        private List<Product> GetProductByRegexToHtml(string url, int navType)
        {
            ProductTypeEnum pEnum = new ProductTypeEnum();
            List<Product> productList = new List<Product>();
            string htmlText = CustomMethod.GetHtmlByHttpHelper(url);
            //获取每个商品 html数据
            string infosRegex = "";
            //if (navType == 1)
            //{
            //    infosRegex = @"<div class=""list list_preferential(\s+)"" timesort=""(.|\s)*?"" articleid=""(.|\s)*?"">(.|\s)*?</div>\s*?<!-- list end -->"; //href='(.*)'
            //}
            //else if (navType == 2)
            //{
            //    infosRegex = @"<div class=""list list_preferential(\s+)"" timesort=""(.|\s)*?"" articleid=""(.|\s)*?"">[\s\S]*?<!-- list -->"; //href='(.*)'
            //    //<div class="list list_preferential" timesort="1441706251" articleid="5_345143">  
            //}
            doc.LoadHtml(htmlText);
            var collec = doc.DocumentNode.SelectNodes("//ul[@class='feed-list-col z-clearfix']/li");

            var list = new List<string>();
            if (collec == null || collec.Count < 1)
            {
                CustomMethod.WriteLog("什么值得买发现，没有获取到商品信息：" + navType);
                return null;
               
            }
            for (int index = 0; index < collec.Count; index++)
            {
                list.Add(collec[index].InnerHtml);
            } 
            //遍历每个商品的html 正则 解析出需要的属性值
            for (int index = 0; index < list.Count; index++)
            {
                try
                {
                    Product product = new Product();
                    product = GetProduct(list[index]);
                    if(product==null)
                    {
                        continue;
                    } 
                    productList.Add(product);
                }
                catch (Exception ex)
                {
                    CustomMethod.WriteLog("什么值得买发现：" + ex.Message.ToString());
                    continue; 
                }
            }
            var newList = CustomMethod.GetDistinctProdcuts(productList);
            newList.Reverse();
            return newList;
        }
        /// <summary>
        ///根据规则获取属性值 一个商品item
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public Product GetProduct(string htmlContent)
        {
            Product pro = new Product();
            pro.FromWeb = "什么值得买发现";
            pro.TypeId = 1;
            pro.UpdateTime = DateTime.Now;
            pro.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            doc.LoadHtml(htmlContent);
            //名称
            var name = CustomMethod.GetValue(doc, "//h5[@class='feed-ver-title']/a");
            if (name == "")
            {
                return null;
            }
            pro.Pname = name;
            //价格
            var pric = CustomMethod.GetValue(doc, "//div[@class='z-highlight z-ellipsis']");
            pro.Price = pric;
            //图片
            var imglis = CustomMethod.GetAttr(doc, htmlContent, "//div[@class='feed-ver-pic']/a/img", "src");
            if (imglis != null && imglis.Count > 0)
            {
                pro.ImgUrl = imglis[0];
            }
            //数据源
            var source = CustomMethod.GetValue(doc, "//a[@class='tag-bottom-right']");
            pro.Source = source;
            //链接
            var outlink = CustomMethod.GetAttr(doc, htmlContent, "//a[@class='z-btn z-btn-red']", "href");
            if (outlink != null && outlink.Count > 0)
            {
                string productUrl = "";
                string link = outlink[0];
                //商品链接 带渠道号
                pro.Plink = CustomMethod.GetEvalUrl(link, ref productUrl, CustomMethod.typeOfWeb.SMZDMFX);
                if (pro.Plink == "")
                {
                    if (productUrl == "")
                    {
                        CustomMethod.WriteLog("smzdm发现：没有抓取到商品链接");

                    }
                    return null;
                }
                //入库前匹配数据库是否存在该商品 商品来源是否重复标识
                pro.Memo = productUrl;
            }
            else
            {
                return null;
            }
            //详细信息
            var detaillink = CustomMethod.GetAttr(doc, htmlContent, "//div[@class='feed-ver-pic']/a", "href");
            if (detaillink != null && detaillink.Count > 0)
            {
                var detail = detaillink[0];
                string htmlDescription = CustomMethod.GetHtmlByHttpHelper(detail);
                doc.LoadHtml(htmlDescription);//详细内容 

                var item = doc.DocumentNode.SelectNodes("//div[@class='baoliao-block']");
                string descr = "";
                if (item != null && item.Count > 0)
                {
                    for (int index = 0; index < item.Count; index++)
                    {
                        string des = item[index].InnerText.Replace("值友", "寐小哥儿");
                        descr += "<p>" + des + "</p><br/>";
                    }
                } 
                pro.Description = descr;
                if (descr=="")
                {
                    pro.Description = pro.Pname;
                }
                //大图
                var bigTu = CustomMethod.GetAttr(doc, htmlDescription, "//img[@itemprop='image']", "src");

                if (bigTu != null && bigTu.Count>0)
                {
                    pro.ImgUrl2 = bigTu[0];
                } 
                //分类  
                doc.LoadHtml(htmlDescription);
                var conllectin = doc.DocumentNode.SelectNodes("//span[@itemprop='title']");//".//a[@href]"
                if (conllectin != null)
                {
                    try
                    {
                        //doc.LoadHtml(conllectin[0].InnerHtml);
                        //var aStr = doc.DocumentNode.SelectNodes("//a");//".//a[@href]"
                        string typstr = conllectin[1].InnerHtml;
                        var tyid = ProductTypeEnum.GetProductType(typstr, typeof(ProductTypeEnum.smzdmType));
                        pro.ProductTypeId = tyid;
                    }
                    catch
                    {
                        pro.ProductTypeId = 16;
                    }
                }
                else
                {
                    pro.ProductTypeId = 16;
                }
            }
            return pro;
        }

    }
}
